<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="员工名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryData">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleInsert">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-upload
							class="upload-demo"
							ref="upload"
							action="http://162.14.115.152:8081/excel/upload"
							:headers="headerObj"
							:on-preview="handlePreview"
							:on-remove="handleRemove"
							:file-list="fileList"
							:auto-upload="false">
						<el-button slot="trigger"  type="primary">选取文件</el-button>
						<el-button style="margin-left: 10px;" type="success" @click="uploadExcel">上传Excel</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="downloadExcel">下载Excel</el-button>
				</el-form-item>

			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" label="序号" width="100">
			</el-table-column>
			<el-table-column prop="username" label="姓名" width="180" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="300" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="180" sortable>
			</el-table-column>
			<el-table-column prop="department.name" label="所在部门" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="query.pageSize" :total="pageInfo.total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑or新增界面-->
		<el-dialog title="编辑/新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="员工姓名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="saveForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input v-model="saveForm.age" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="所在部门" prop="department" >
					<el-cascader v-model="saveForm.department"
								 :options="deptTree"
								 :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
								 clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	export default {
		data() {
			return {
				headerObj: {
					token: localStorage.getItem("token")
				},
				fileList:[],
				//分页显示的数据
				pageInfo:{
					total:0,
					data:[]
				},
				//分页查找的参数
				query:{
					keyword:'',
					pageSize: 5,
					currentPage:1
				},
				listLoading: false,
				sels: [],//列表选中列
				employees:[],//员工（管理员）列表
				deptTree:[],//部门列表
				saveFormVisible: false,//编辑/新增界面是否显示
				saveLoading: false,
				saveFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑/新增界面数据
				saveForm: {
					id: null,
					username: '',
					age:'',
					email:'',
					department:{
						id: null,
						name:"",
						path:""
					}
				},
			}
		},
		methods: {
			downloadExcel(){
				this.$http.post('/excel/download',this.query,{
					responseType: 'blob' // 表明返回服务器返回的数据类型
				})
						.then((res) => { // 处理返回的文件流
							let blob = new Blob([res.data], {type: res.data.type})
							const fileName = 'easypoi.xlsx';
							let downloadElement = document.createElement('a')
							let href = window.URL.createObjectURL(blob); //创建下载的链接
							downloadElement.href = href;
							downloadElement.download = fileName; //下载后文件名
							document.body.appendChild(downloadElement);
							downloadElement.click(); //点击下载
							document.body.removeChild(downloadElement); //下载完成移除元素
							window.URL.revokeObjectURL(href); //释放blob
							message.success('upload successfully.');
						})
						.catch(function (error) {
							console.log(error);
						});
			},
			uploadExcel() {
				this.$refs.upload.submit();
			},
			handleRemove(file, fileList) {
				console.log(file, fileList);
			},
			handlePreview(file) {
				console.log(file);
			},
			//获取部门列表方法
			getDepartment(){
				this.$http.get("/department/parent")
						.then(res=>{
							res = res.data;
							this.deptTree = res.data;
						}).catch(() => {

				});
			},
			//分页工具栏事件
			handleCurrentChange(val) {
				//当前页
				this.query.currentPage = val;
				this.queryData();
			},
			//分页高级查询搜索方法
			queryData(){
				this.$http.post("/employee",this.query)
						.then(res=>{
							res = res.data
							this.pageInfo = res.data;
							this.query.currentPage = 1;

						}).catch(() => {

				});
			},

			//删除事件
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.deleteById(row.id);
				}).catch(() => {

				});
			},
			//通过ID删除数据方法
			deleteById(id){
				this.$http.delete("/employee/"+id,{})
						.then(res=>{
							res = res.data;
							this.listLoading = false;
							//重置当前页为第一页
							this.query.currentPage = 1;
							this.queryData();
							if (res.success){
								this.$message({
									message: res.msg,
									type: 'success'
								});
							}
						})
						.catch(res=>{

						})
			},

			//显示编辑界面
			handleEdit: function (index, row) {
				let obj = Object.assign({}, row);
				this.saveForm = obj;
				if (!obj.department){
					this.saveForm.department = {}
				}
				// 父部门回显
				let temp = [];
				if(obj.department.path){
					let array = obj.department.path.split("/");
					//需要当前的ID（当前部门）
					for(let i=1;i<array.length;i++){
						temp.push(parseInt(array[i]));
					}
				}
				this.saveForm.department = temp;

				//显示部门列表
				this.getDepartment();
				//显示编辑界面
				this.saveFormVisible = true;
			},
			//显示insert界面
			handleInsert(){
				//清空
				this.saveForm = {
					id: null,
					username: '',
					age:'',
					email:'',
					department:{
						id: null,
						name:"",
					}
				}
				// //显示部门列表
				this.getDepartment();
				this.saveFormVisible = true;
			},

			//编辑or新增确认框
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							//NProgress.start();

							this.saveData();

						});
					}
				});
			},

			//编辑or新增请求方法
			saveData(){
				this.query.keyword = "";
				var form = this.saveForm;
				//将数组转换成对象
				if (form.department){
					this.saveForm.department = {
						id: form.department[form.department.length-1]
					}
				}
				this.$http.put("/employee",this.saveForm)
						.then(res=>{
							res = res.data;
							this.saveFormVisible = false;
							this.saveLoading =false;
							this.queryData();
							if (res.success){
								this.$message({
									message: res.msg,
									type: 'success'
								});
							}
						})
						.catch(res=>{

						})
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除事件
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.query.currentPage = 1;
					//NProgress.start();
					this.batchDelete(ids)
				}).catch(() => {

				});
			},
			//通过ID删除数据方法
			batchDelete(ids){
				this.$http.patch("/employee",ids)
						.then(res=>{
							res = res.data;
							this.listLoading = false;
							this.queryData();
							if (res.success){
								this.$message({
									message: res.msg,
									type: 'success'
								});
							}
						})
						.catch(res=>{

						})
			},
		},
		mounted() {
			this.queryData();
		}
	}

</script>

<style scoped>

</style>